package com.ajhlp.app.phoneDetailQuery.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ajhlp.app.phoneDetailQuery.model.ConfigurationNameEnum;
import com.ajhlp.app.phoneDetailQuery.service.IConfigModifyService;

@Controller
public class FileDownloadController {
	
	private Logger log = Logger.getLogger(getClass());

	@RequestMapping(value = "/download")
	public void download(String name, HttpServletResponse response) {
		log.debug("download controller");
		File file = new File(
				IConfigModifyService.configProperties.get(ConfigurationNameEnum.SAVE_PATH.getName())
						+ name);
		log.debug("download File:"+file.getAbsolutePath());
		if (file.exists()) {
			// 设置response的编码方式
			response.setContentType("application/x-msdownload");

			// 写明要下载的文件的大小
			response.setContentLength((int) file.length());

			// 设置附加文件名
			// response.setHeader("Content-Disposition","attachment;filename="+filename);

			// 解决中文乱码
			try {
				response.setHeader("Content-Disposition",
						"attachment;filename=" + new String

						(name.getBytes("gbk"), "iso-8859-1"));
			} catch (UnsupportedEncodingException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			log.debug("set response params");
			try {
				FileUtils.copyFile(file, response.getOutputStream());
				
				response.getOutputStream().flush();
				
				response.getOutputStream().close();
				
				log.debug("response writed");
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
			} catch (IOException e) {
				// TODO Auto-generated catch block
			}
		}
	}
}
